#include "_stdio.h"


_FILE* _fopen(const char* filename,const char* mode)       //模拟fopen
{
    int flags=0;
    if(strcmp(mode,"w") == 0)
    {
        flags |= (O_WRONLY | O_CREAT | O_TRUNC);
    }
    else if(strcmp(mode,"r") == 0)
    {
        flags |= O_RDONLY;
    }
    else if(strcmp(mode,"a") == 0)
    {
        flags |= (O_WRONLY | O_CREAT | O_APPEND);
    }
    //上面在确认文件打开方式

    int fd=0;
    if(flags & O_RDONLY) fd=open(filename,flags);
    else fd=open(filename,flags,0666);
    if(fd < 0)
    {
        const char* msg=strerror(errno);
        write(1,msg,strlen(msg));
        return NULL;    //创建文件失败
    }
    //上面在创建文件


    _FILE* fp = (_FILE*)malloc(sizeof(_FILE));
    fp->flags=LINE;     //默认行刷新
    fp->fileno=fd;
    fp->size=0;
    fp->cap=SIZE;
    memset(fp->cush,0,SIZE);
    //上面在初始化_FILE结构体

    return fp; 
}


void _fclose(_FILE* fp)     //模拟fclose
{
   _fflush(fp);
   close(fp->fileno);
}



void _fflush(_FILE* fp)        //模拟fflush
{
    if(fp->size > 0)
    {
        write(fp->fileno,fp->cush,fp->size);
        fp->size=0;
    }
}


void _fwrite(const char* msg,int size,int len,_FILE* fp)     //模拟fwrite
{
    //size没什么乱用，对齐fwrite而已
    
    memcpy(fp->cush+fp->size,msg,len);
    fp->size+=len;

    //行刷新
    if(fp->cush[fp->size-1] == '\n')
    {
        write(fp->fileno,fp->cush,fp->size);
        fp->size=0;
    }
    else if(fp->size == fp->cap)
    {
        write(fp->fileno,fp->cush,fp->size);
        fp->size=0;
    }

}
